import axios from 'axios'
// import router from '../router/index'
import store from '@/store'
import router from '../router/index'
// import NProgress from 'nprogress'
import { Loading, Notification } from 'element-ui'
import { sendMsgEvent, EVENT_TYPE } from '@utility/eventBus'
import { Session, Local } from '@utility/storage.js'
import { debounce } from '@utility/utility'
import { GET_TENANT_ID } from '@utility/constant.js'

axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 60000

let loading
// 内存中正在请求的数量
let loadingNum = 0

function startLoading() {
  if (loadingNum === 0) {
    loading = Loading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(255,255,255,0.5)',
    })
  }
  // 请求数量加1
  loadingNum++
}

function endLoading() {
  // 请求数量减1
  if (loadingNum > 0) {
    loadingNum--
  }
  if (loadingNum <= 0) {
    loading && loading.close()
  }
}

const showErrMsg = debounce(err => {
  showErrNotification(err)
  // NProgress.done()
}, 1200)

// 请求数据拦截器
axios.interceptors.request.use(
  config => {
    // config.headers.hideLoading = true
    const userId = Local.get('userId')
    if (userId) {
      config.headers.id = Local.get('userId')
    }
    // 统一增加Authorization请求头, skipToken 跳过增加token
    const token = Session.getToken()
    if (token && !config.headers?.skipToken) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 统一增加TENANT-ID请求头
    const tenantId = Session.get('tenantId') || GET_TENANT_ID()
    if (tenantId) {
      config.headers['Tenant-Id'] = tenantId
    }

    if (!config.headers.hideLoading) {
      startLoading()
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 接收响应拦截器
axios.interceptors.response.use(
  response => {
    endLoading()
    if (response.headers['content-type'].includes('download') || response.headers['content-type'].includes('stream')) {
      if (response.code === 1) {
        showErrMsg(response.data)
      }
    } else if (response.data.code === 1) {
      showErrMsg(response.data)
      if (response.data.status === '501') {
        sendMsgEvent(EVENT_TYPE.goLogin)
        store.dispatch('user/clearUserInfo')
        localStorage.clear()
        sessionStorage.clear()
        router.replace({
          path: '/login',
          // params: { showLogin: true },
        })
      }
    }

    return response
  },
  err => {
    endLoading()
    showErrMsg(err.response)
    return Promise.reject(err)
  }
)

export const GET = async (url, params) => {
  const res = await axios.get(url, {
    params,
  })
  if (res.headers['content-type'].includes('download') || res.headers['content-type'].includes('stream')) {
    return res
  }
  return res.data
}

export const POST = async (url, params, config = {}) => {
  const res = await axios.post(url, params || {}, {
    ...config,
  })
  if (res.headers['content-type'].includes('download')) {
    return res
  }
  return res.data
}

export const PUT = async (url, params, config = {}) => {
  const res = await axios.put(url, params || {}, {
    ...config,
  })
  if (res.headers['content-type'].includes('download')) {
    return res
  }
  return res.data
}

export const DELETE = async (url, params) => {
  const res = await axios.delete(url, {
    data: params,
  })
  return res.data
}

function showErrNotification(err) {
  let errMsg = err && (err.msg || err.message)
  if (!errMsg && err && err.status) {
    switch (err.status) {
      case 400:
        errMsg = '请求错误(400)'
        break
      case 401:
        errMsg = err?.data.msg
        break
      case 403:
        errMsg = '拒绝访问(403)'
        break
      case 404:
        errMsg = '请求出错(404)'
        break
      case 408:
        errMsg = '请求超时(408)'
        break
      case 424:
        // 没有访问权限
        errMsg = err?.data.msg
        store.dispatch('user/clearUserInfo')
        localStorage.clear()
        router.replace({
          path: '/login',
        })
        break
      case 500:
        errMsg = '服务器错误(500)'
        break
      case 501:
        errMsg = '服务未实现(501)'
        break
      case 502:
        errMsg = '网络错误(502)'
        break
      case 503:
        errMsg = '服务不可用(503)'
        break
      case 504:
        errMsg = '网络超时(504)'
        break
      case 505:
        errMsg = 'HTTP版本不受支持(505)'
        break
      default:
        errMsg = `请求出错(${err.status})!`
    }
  }
  Notification.error({
    title: '错误',
    message: errMsg || '服务器错误',
    duration: 2000,
  })
}
